<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="统计时间范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="班级" prop="classCode">
        <el-select
          v-model="queryParams.classCode"
          placeholder="请选择班级"
          clearable
          style="width: 200px"
          @change="handleClassCodeChange"
        >
          <el-option
            v-for="dict in classList"
            :key="dict.classCode"
            :label="dict.className"
            :value="dict.classCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">统计</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="!statisticsData.length"
        >导出统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="handleQuery"></right-toolbar>
    </el-row>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="mb20" v-if="statisticsData.length">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总学生数</span>
          </div>
          <div class="text item">
            <span class="count">{{ totalStudents }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总作业数</span>
          </div>
          <div class="text item">
            <span class="count">{{ totalHomeworks }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>平均提交率</span>
          </div>
          <div class="text item">
            <span class="count">{{ averageSubmissionRate }}%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>未交作业总数</span>
          </div>
          <div class="text item">
            <span class="count text-danger">{{ totalUnsubmitted }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计表格 -->
    <el-table v-loading="loading" :data="statisticsData" border>
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="姓名" align="center" prop="studentName" width="100" />
      <el-table-column label="学号" align="center" prop="studentNo" width="120" />
      <el-table-column 
        v-for="homework in homeworkDates" 
        :key="homework.date"
        :label="homework.dateLabel"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <el-tag 
            v-if="getHomeworkStatus(scope.row, homework.date)"
            :type="getHomeworkTagType(getHomeworkStatus(scope.row, homework.date))"
            size="mini"
          >
            {{ getHomeworkStatusText(getHomeworkStatus(scope.row, homework.date)) }}
          </el-tag>
          <el-tag v-else type="danger" size="mini">未交</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交率" align="center" width="80">
        <template slot-scope="scope">
          <span :class="{'text-danger': scope.row.submissionRate < 80}">
            {{ scope.row.submissionRate }}%
          </span>
        </template>
      </el-table-column>
      <el-table-column label="已交" align="center" width="60">
        <template slot-scope="scope">
          <span class="text-success">{{ scope.row.submittedCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未交" align="center" width="60">
        <template slot-scope="scope">
          <span class="text-danger">{{ scope.row.unsubmittedCount }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { listSubmit } from "@/api/manage/submit"
import { listClass } from "@/api/manage/class"
import { listStudent } from "@/api/manage/student"

export default {
  name: "SubmitStatistics",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 班级列表
      classList: [],
      // 统计数据
      statisticsData: [],
      // 作业日期列表
      homeworkDates: [],
      // 查询参数
      queryParams: {
        dateRange: [],
        classCode: null
      },
      // 统计概览数据
      totalStudents: 0,
      totalHomeworks: 0,
      averageSubmissionRate: 0,
      totalUnsubmitted: 0
    }
  },
  created() {
    this.getClassList()
    // 默认查询最近30天的数据
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(startDate.getDate() - 30)
    this.queryParams.dateRange = [
      this.formatDate(startDate),
      this.formatDate(endDate)
    ]
  },
  methods: {
    /** 查询班级列表 */
    getClassList() {
      listClass().then(response => {
        this.classList = response.rows || []
      })
    },
    /** 格式化日期 */
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    /** 统计查询 */
    handleQuery() {
      if (!this.queryParams.dateRange || this.queryParams.dateRange.length !== 2) {
        this.$modal.msgError("请选择统计时间范围")
        return
      }
      
      this.loading = true
      this.getStatisticsData()
    },
    /** 班级选择改变事件 */
    handleClassCodeChange(classCode) {
      // 更新upload.data中的classCode
      this.queryParams.classCode = classCode || ''
    },
    /** 获取统计数据 */
    async getStatisticsData() {
      try {
        // 构建查询参数
        const params = {
          startDate: this.queryParams.dateRange[0],
          endDate: this.queryParams.dateRange[1],
          classCode: this.queryParams.classCode
        }
        
        // 获取提交记录数据
        const submitResponse = await listSubmit({
          ...params,
          pageNum: 1,
          pageSize: 10000 // 获取所有数据
        })
        
        // 获取学生列表
        const studentResponse = await listStudent({
          classCode: this.queryParams.classCode,
          pageNum: 1,
          pageSize: 10000
        })
        
        this.processStatisticsData(submitResponse.rows || [], studentResponse.rows || [])
        
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$modal.msgError("获取统计数据失败")
      } finally {
        this.loading = false
      }
    },
    /** 处理统计数据 */
    processStatisticsData(submitData, studentData) {
      // 获取所有作业日期
      const dates = [...new Set(submitData.map(item => item.submitDate))].sort()
      this.homeworkDates = dates.map(date => ({
        date: date,
        dateLabel: this.formatDateLabel(date)
      }))
      
      // 按学生分组统计
      const studentStats = {}
      
      // 初始化学生统计数据
      studentData.forEach(student => {
        studentStats[student.studentNo] = {
          studentNo: student.studentNo,
          studentName: student.studentName,
          submissions: {},
          submittedCount: 0,
          unsubmittedCount: 0,
          submissionRate: 0
        }
      })
      
      // 填充提交数据
      submitData.forEach(submit => {
        if (studentStats[submit.studentNo]) {
          studentStats[submit.studentNo].submissions[submit.submitDate] = submit.submitStatus
        }
      })
      
      // 计算统计数据
      Object.keys(studentStats).forEach(studentNo => {
        const student = studentStats[studentNo]
        const totalHomeworks = this.homeworkDates.length
        
        student.submittedCount = Object.values(student.submissions).filter(status => status === '已提交').length
        student.unsubmittedCount = totalHomeworks - student.submittedCount
        student.submissionRate = totalHomeworks > 0 ? Math.round((student.submittedCount / totalHomeworks) * 100) : 0
      })
      
      this.statisticsData = Object.values(studentStats)
      this.calculateOverviewData()
    },
    /** 计算概览数据 */
    calculateOverviewData() {
      this.totalStudents = this.statisticsData.length
      this.totalHomeworks = this.homeworkDates.length
      this.totalUnsubmitted = this.statisticsData.reduce((sum, student) => sum + student.unsubmittedCount, 0)
      
      if (this.statisticsData.length > 0) {
        const totalRate = this.statisticsData.reduce((sum, student) => sum + student.submissionRate, 0)
        this.averageSubmissionRate = Math.round(totalRate / this.statisticsData.length)
      } else {
        this.averageSubmissionRate = 0
      }
    },
    /** 格式化日期标签 */
    formatDateLabel(dateStr) {
      const date = new Date(dateStr)
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${month}.${day}`
    },
    /** 获取作业状态 */
    getHomeworkStatus(student, date) {
      return student.submissions[date] || null
    },
    /** 获取作业状态标签类型 */
    getHomeworkTagType(status) {
      switch(status) {
        case '未交': return 'danger'
        case '已提交': return 'success'
        case '迟交': return 'warning'
        default: return 'info'
      }
    },
    /** 获取作业状态文本 */
    getHomeworkStatusText(status) {
      switch(status) {
        case '已提交': return '✓'
        case '迟交': return '△'
        case '未交': return '✗'
        default: return '✗'
      }
    },
    /** 重置查询 */
    resetQuery() {
      this.resetForm("queryForm")
      this.statisticsData = []
      this.homeworkDates = []
      this.totalStudents = 0
      this.totalHomeworks = 0
      this.averageSubmissionRate = 0
      this.totalUnsubmitted = 0
    },
    /** 导出统计数据 */
    handleExport() {
      // 构建导出数据
      const exportData = this.statisticsData.map(student => {
        const row = {
          '姓名': student.studentName,
          '学号': student.studentNo
        }
        
        // 添加每个作业日期的状态
        this.homeworkDates.forEach(homework => {
          const status = this.getHomeworkStatus(student, homework.date)
          row[homework.dateLabel] = status || '未交'
        })
        
        row['提交率'] = student.submissionRate + '%'
        row['已交'] = student.submittedCount
        row['未交'] = student.unsubmittedCount
        
        return row
      })
      
      // 这里可以调用导出API或使用前端导出库
      console.log('导出数据:', exportData)
      this.$modal.msgSuccess("导出功能开发中...")
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.count {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.text-danger {
  color: #F56C6C;
}

.text-success {
  color: #67C23A;
}

.mb20 {
  margin-bottom: 20px;
}
</style>